import 'dart:ui';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../controller/home/home_logic.dart';
import '../../resources/colours.dart';
import '../../resources/styles.dart';
import '../../utils/mode_config.dart';
import '../../utils/routes.dart';
import '../../utils/user.dart';
import '../../widgets/gif.dart';
import '../../widgets/base/qkd_text.dart';

class SearchRectTween extends RectTween {
  SearchRectTween(Rect? begin, Rect? end) : super(begin: begin, end: end);

  @override
  Rect lerp(double t) {
    double left = lerpDouble(begin?.left, end?.left, t) ?? 0;
    double bottom = begin?.bottom ?? 0;
    double right = end?.right ?? 0;
    double top = begin?.top ?? 0;

    return Rect.fromLTRB(left, top, right, bottom);
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  final HomeLogic logic = Get.put(HomeLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<HomeLogic>(builder: (logic) {
      return AnnotatedRegion<SystemUiOverlayStyle>(
        value: const SystemUiOverlayStyle(
            statusBarBrightness: Brightness.dark,
            statusBarIconBrightness: Brightness.dark),
        child: Scaffold(
          body: VisibilityDetector(
            key: const Key("home"),
            onVisibilityChanged: (VisibilityInfo info) {
              if (!info.visibleBounds.isEmpty) {
                logic.getMsgCount();
                logic.getLive();
              }
            },
            child: Container(
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colours.white, Colours.greyF2F3F7],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    stops: [0.2, 0.4]),
              ),
              child: LoadingWidget<bool>(
                isLoading: logic.pages.noValue,
                loading: Container(),
                data: false,
                reconnect: logic.getRefresh,
                child: () => Stack(
                  alignment: Alignment.topCenter,
                  children: [
                    Image.asset(Utils.getImgPath("nav_head_back.png"),
                        width: Get.width, height: Get.width * 128 / 375),
                    SafeArea(
                      child: Column(children: [
                        SizedBox(
                          height: 44,
                          child: Row(
                            children: [
                              Container(width: 8),
                              Expanded(
                                child: GestureDetector(
                                  onTap: () => Get.toNamed(Routes.search),
                                  child: Hero(
                                    tag: "searchBar",
                                    createRectTween: (begin, end) =>
                                        SearchRectTween(begin, end),
                                    child: SizedBox(
                                      height: 34,
                                      child: TextField(
                                        enabled: false,
                                        maxLines: 1,
                                        style: const TextStyle(fontSize: 16),
                                        strutStyle:
                                            const StrutStyle(fontSize: 18),
                                        cursorColor: Colours.main,
                                        decoration: InputDecoration(
                                            filled: true,
                                            isCollapsed: true,
                                            fillColor: Colours.white,
                                            contentPadding:
                                                const EdgeInsets.only(top: 4),
                                            prefixIcon: Padding(
                                              padding: const EdgeInsets.all(6),
                                              child: Image.asset(
                                                  Utils.getImgPath(
                                                      "search.png"),
                                                  color: Colours.grey99,
                                                  width: 16,
                                                  height: 16),
                                            ),
                                            border: const OutlineInputBorder(
                                                borderSide: BorderSide.none,
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(35 / 2))),
                                            hintText:
                                                "搜索${ModeConfig.expert ? "专家、方案、" : ""}赛事、球队等",
                                            hintStyle: const TextStyle(
                                                fontSize: 14, height: 1.4)),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              Container(width: 16),
                              GestureDetector(
                                  onTap: () async {
                                    Utils.onEvent('znx', params: {'znx': 0});
                                    User.needLogin(() async =>
                                        await Get.toNamed(Routes.myMsg));
                                  },
                                  child: Image.asset(
                                    Utils.getImgPath('my_msg.png'),
                                    width: 24,
                                    color: Colors.black,
                                  ).badge(
                                      logic.unreadCount != 0
                                          ? "${logic.unreadCount > 99 ? "99+" : logic.unreadCount}"
                                          : null,
                                      color: Colours.main,
                                      textColor: Colours.white)),
                              Container(width: 16)
                            ],
                          ),
                        ),
                        Row(
                          children: [
                            Expanded(
                              child: SizedBox(
                                height: 40,
                                child: Styles.tabbar(
                                    scrollable: true,
                                    labelColor: Colours.text,
                                    fontSize: 16,
                                    controller: logic.tabController,
                                    onTap: (value) {
                                      logic.index = value;
                                      Utils.onEvent('home_channel', params: {
                                        'home_channel':
                                            logic.classes![value].name
                                      });
                                    },
                                    labelPadding: const EdgeInsets.symmetric(
                                        horizontal: 9),
                                    tabs: logic.classes!.map((e) {
                                      if (e.id == "app_live" && logic.hasLive) {
                                        return Row(
                                          children: [
                                            QkdText(e.name ?? ""),
                                            const GifWidget(
                                                width: 16,
                                                height: 16,
                                                asset: 'in_live_48.gif',
                                                duration:
                                                    Duration(milliseconds: 500))
                                          ],
                                        );
                                      } else {
                                        return QkdText(e.name ?? "");
                                      }
                                    }).toList()),
                              ),
                            ),
                            Container(
                              height: 34,
                              width: 1,
                              decoration: BoxDecoration(boxShadow: [
                                BoxShadow(
                                    color: Colours.grey80.withOpacity(0.2),
                                    offset: const Offset(0, 0),
                                    blurRadius: 3.5,
                                    spreadRadius: 0.2)
                              ]),
                            ),
                            Container(
                              width: 46,
                              height: 40,
                              alignment: Alignment.center,
                              child: Image.asset(
                                  width: 16,
                                  Utils.getImgPath("my_channel.png")),
                            ).tap(() async {
                              logic.onTapFilter();
                            })
                          ],
                        ),
                        const Divider(color: Colours.greyEE, height: 0.5),
                        Expanded(
                          child: ExtendedTabBarView(
                              controller: logic.tabController,
                              children: logic.pages),
                        )
                      ]),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    });
  }

  @override
  bool get wantKeepAlive => true;
}
